package main

import (
	"context"
	"fmt"
	"gitee.com/shijun123456/rpcVotes/test/server"
	"google.golang.org/grpc"
	"io"
	"log"
	"os"
	"time"
)

func main() {
	grpcConn, err := grpc.Dial("127.0.0.1"+":6012", grpc.WithInsecure())
	if err != nil {
		log.Fatalln(err)
	}
	logincClient := server.NewLoginClient(grpcConn)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	res, err := logincClient.Login(ctx, &server.LoginReq{
		Username: "root",
		Password: "123456",
	})
	if err != nil {
		log.Fatalln(err)
	}
	log.Println("the login answer is", res.Msg)

	//客户端流处理方式
	uploadClient := server.NewUploadClient(grpcConn)

	uploadStramCli, err := uploadClient.Upload(ctx)
	if err != nil {
		log.Fatalln(err)
	}

	var offset int64
	var size int64
	size = 4 * 1024

	var totalSize int64
	fieinfo, err := os.Stat("test.txt")
	if err != nil {
		log.Println(err.Error())
		return
	}

	totalSize = fieinfo.Size()
	fmt.Println(totalSize)

	//客户端流
	for {
		data, err2 := readfilecontent("./test.txt", offset+size)
		offset += size
		if err2 != nil {
			if err2 == io.EOF {
				err := uploadStramCli.Send(&server.UploadReq{
					Path:   "./test.txt",
					Offset: offset,
					Size:   size,
					Data:   data,
				})
				if err != nil {
					log.Fatalln(err)
				}
				fmt.Println(string(data))
				res, err := uploadStramCli.CloseAndRecv()
				if err != nil {
					log.Fatalln(err)
				}
				log.Println("upload server over~,response is", res.Msg)
				break
			}
		}
		err = uploadStramCli.Send(&server.UploadReq{
			Path:   "./test.txt",
			Offset: offset,
			Size:   size,
			Data:   data,
		})

		if err != nil {
			log.Fatalln(err)
		}

	}
}

//客户端流读取 文件的信息
//枚举句柄

//文件的名称
func readfilecontent(filename string, offset int64) ([]byte, error) {
	var buf = make([]byte, 4*1024) //每次装入 4*1024 偏移量是 4024 如果没有 则小于这个则 :n 即可
	file, err := os.OpenFile(filename, os.O_RDONLY, 0666)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	fmt.Printf("offset:%d\n", offset)
	n, err := file.ReadAt(buf, offset)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("offset:%d\n",offset)
	//fmt.Println(string(buf[:n]))
	return buf[:n], nil
}
